<?php

namespace uniadmin\openapi;

use think\Route;
use think\Service;
use think\Validate;

class UiService extends Service
{
    public function boot()
    {
        $this->registerRoutes(function (Route $route) {
            // 分组
            $route->get('/openapi/group$', function() {
                $group = [];
                $group[] = [
                    "name" => config("openapi.name"),
                    "basePath" => $_SERVER['HTTP_HOST'],
                    "url" => "/openapi/doc.json",
                    "swaggerVersion" => "3.0"
                ];
                echo json_encode($group);
            })->ext('json');

            // 默认文档
            $route->get('/openapi/doc$', function() {
                $openapi = \OpenApi\scan(base_path());
                header('Content-Type: application/json');
                echo $openapi->toJson();
            })->ext('json');

            // ui访问
            $route->get('/doc$', function() {
                $index = file_get_contents(dirname(__FILE__) . "/ui/doc.html");
                header('Content-Type: text/html');
                echo $index;
            });

            // ui访问
            $route->get('/doc/$', function() {
                $index = file_get_contents(dirname(__FILE__) . "/ui/doc.html");
                header('Content-Type: text/html');
                echo $index;
            });

            // 拦截
            $route->get('/openapi-ui/<name>', function() {
                $index = file_get_contents(dirname(__FILE__) . "/ui/" . substr(request()->pathinfo() , 11));
                header('Content-Type: text/' . request()->ext());
                echo $index;
            })->pattern(['name' => '[a-zA-Z]+', 'id' => '\d+']);
        });
    }
}